﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using Dapper;
using System.Data;
using System.Text.RegularExpressions;
using _180FrameWork.DataBaseHelper.Entities;

namespace _180FrameWork.DataBaseHelper.MySqlExtend
{
    public class MySqlJintDB : JintDB, IJintDB
    {
        public MySqlJintDB(string DBConnectionString)
        {
            _db = new GenericDatabase(DBConnectionString, MySql.Data.MySqlClient.MySqlClientFactory.Instance);
            _paramChar = "?";
        }

        #region Dapper

        /// <summary>
        /// 查询分页
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="sort"></param>
        /// <param name="order"></param>
        /// <returns></returns>
        public override PageData<dynamic> Page(string sql, IDictionary<string, object> param)
        {
            int page = 1; int rows = 20; string sort = ""; string order = ""; int total = 0; string SUM = "";
            foreach (KeyValuePair<string, object> item in param)
            {
                switch (item.Key)
                {
                    case "page":
                        page = Convert.ToInt32(item.Value);
                        break;
                    case "rows":
                        rows = Convert.ToInt32(item.Value);
                        break;
                    case "sort":
                        sort = Convert.ToString(item.Value);
                        break;
                    case "order":
                        order = Convert.ToString(item.Value);
                        break;
                    case "total":
                        total = Convert.ToInt32(item.Value);
                        break;
                    case "sum":
                        SUM = Convert.ToString(item.Value);
                        break;
                    //default:
                    //    dp.Add(item.Key, item.Value);
                    //    break;
                }
            }
            var dp = GetParams(sql, param,false);
            var p = new PageData<dynamic>();
            if (total != 0)
            {
                p.total = total;
            }
            else
            {
                string strTotalSql = "select count(*) from(" + sql + ") t";
                p.total = this.Conn.ExecuteScalar<int>(strTotalSql, dp);
                if (p.total == 0)
                    p.total = 1;
            }
            p.totalPages = (p.total / rows) + (p.total % rows > 0 ? 1 : 0);
            //汇总
            if (SUM != "")
            {
                string strSumSql = "select " + SUM + " from(" + sql + ") t";
                p.footer = this.Conn.Query(strSumSql, dp).ToList();
            }
            //排序
            string orderby = "";
            if (sort != "")
            {
                orderby = " order by " + sort;
                if (order != "")
                {
                    orderby += " " + order;
                }
            }


            //获取分页数据
            int beginrow = rows * (page - 1) + 1;
            int endrow = rows * page;
            dp.Add("beginrow", beginrow);
            dp.Add("endrow", endrow);
            dp.Add("pagesize", rows);
            string strDataSql = sql + orderby + " limit ?beginrow,?pagesize";
            p.rows = this.Conn.Query(strDataSql, dp).ToList();
            //p.footer=this.Conn.Query(
            return p;

        }
        /// <summary>
        /// 存储过程
        /// </summary>
        /// <param name="spName"></param>
        /// <param name="param"></param>
        public override IDictionary<string, object> Sp(string spName, IDictionary<string, object>[] param) { return null; }

        protected override DynamicParameters GetParams(string SQL, IDictionary<string, object> data, bool StrToDateTime)
        {
            var param = new DynamicParameters();
            if (this._paramChar != "")
            {
                var mapList = Regex.Matches(SQL, @"\" + this._paramChar + @"\w+").Cast<Match>().Select(m => m.Value).Distinct().ToArray();

                foreach (KeyValuePair<string, object> prop in data)
                {
                    foreach (var Key in mapList)
                    {
                        if (Key.ToUpper() == this._paramChar + prop.Key.ToUpper())
                        {
                            if (prop.Value != null)
                            {
                                if (prop.Value.GetType().Name.ToUpper() == "STRING")
                                {
                                    param.Add(Key, new DbString() { Value = prop.Value.ToString(), IsAnsi = true });
                                }
                                else
                                {
                                    param.Add(Key, prop.Value);
                                }
                            }
                            else
                            {
                                param.Add(Key, null);
                            }
                        }
                    }
                }
            }
            
            return param;
        }

        protected override DataBaseTableSchedule GetTableSchedule(string tableName, IDbTransaction tran)
        {
            return null;
        }

        //protected override IList<string> GetPKList(string tableName, IDbTransaction tran)
        //{
        //    return null;
        //}
        #endregion

    }
}
